package cn.aylog.controller;

import cn.aylog.pojo.Account;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AccountController {

    Logger LOG = LoggerFactory.getLogger(AccountController.class);

    @RequestMapping("/login")
    public String login(Account account) throws JsonProcessingException {
        LOG.info("method:[login] -> args: " + account);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account.getUsername(), account.getPassword());
        Map<String, Object> map = new HashMap<>();
        try {
            subject.login(token);
            map.put("success", true);
            map.put("message", "登录成功");
            LOG.info("登录成功");
        } catch (IncorrectCredentialsException e) {
            map.put("success", false);
            map.put("message", "密码错误");
            LOG.error(e.getMessage());
        } catch (UnknownAccountException e) {
            map.put("success", false);
            map.put("message", "用户名不存在");
            LOG.error(e.getMessage());
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "登录失败");
            LOG.error(e.getMessage());
        }
        return new ObjectMapper().writeValueAsString(map);
    }

    @RequestMapping("/logout")
    public String logout() throws JsonProcessingException {
        SecurityUtils.getSubject().logout();
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("message", "登出成功");
        return new ObjectMapper().writeValueAsString(map);
    }
}
